<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Kafka WebSocket Visualization (Cumulative with Charts)</title>
  <script src="https://cdn.socket.io/4.6.1/socket.io.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
  <style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    .container { display: flex; flex-wrap: wrap; gap: 20px; }
    .chart-container { width: 48%; height: 400px; }
  </style>
</head>
<body>
  <h1>Kafka WebSocket Visualization (Cumulative)</h1>

  <div class="container">
    <!-- 图表 1: 累计展示所有男女人数各自的总和 -->
    <div class="chart-container" id="gender-total-chart"></div>

    <!-- 图表 2: 累计展示各个学期男女人数总和 -->
    <div class="chart-container" id="semester-total-chart"></div>

    <!-- 图表 3: 累计展示在籍和不在籍男女生人数 -->
    <div class="chart-container" id="in-school-status-chart"></div>

    <!-- 图表 4: 各个班级的男女的人数 (饼状图) -->
    <div class="chart-container" id="class-gender-pie-chart"></div>

    <!-- 图表 5: 不同学期各个班级的男女的人数 (柱状图) -->
    <div class="chart-container" id="semester-class-gender-bar-chart"></div>
  </div>

  <script>
    const socket = io('http://localhost:5000');

    // 全局累计数据
    const cumulativeData = {
      genderTotal: { male: 0, female: 0, total: 0 },
      semesterTotal: {}, // { semester: { male: count, female: count } }
      inSchoolStatus: { inSchool: { male: 0, female: 0 }, notInSchool: { male: 0, female: 0 } },
      classGender: {}, // { class: { male: count, female: count } }
      semesterClassGender: {}, // { semester: { class: { male: count, female: count } } }
    };

    // 初始化 ECharts 图表实例
    const genderTotalChart = echarts.init(document.getElementById('gender-total-chart'));
    const semesterTotalChart = echarts.init(document.getElementById('semester-total-chart'));
    const inSchoolStatusChart = echarts.init(document.getElementById('in-school-status-chart'));
    const classGenderPieChart = echarts.init(document.getElementById('class-gender-pie-chart'));
    const semesterClassGenderBarChart = echarts.init(document.getElementById('semester-class-gender-bar-chart'));

    // 图表配置
    const genderTotalChartOption = {
      title: { text: '累计所有男女人数总和', left: 'center' },
      tooltip: { trigger: 'item' },
      series: [
        {
          name: '人数',
          type: 'pie',
          radius: '50%',
          data: []
        }
      ]
    };
    genderTotalChart.setOption(genderTotalChartOption);

    const semesterTotalChartOption = {
      title: { text: '累计各个学期男女人数总和', left: 'center' },
      tooltip: { trigger: 'axis' },
      legend: { top: 'bottom' },
      xAxis: { type: 'category', data: [] },
      yAxis: { type: 'value' },
      series: [
        { name: '男', type: 'bar', data: [] },
        { name: '女', type: 'bar', data: [] }
      ]
    };
    semesterTotalChart.setOption(semesterTotalChartOption);

    const inSchoolStatusChartOption = {
      title: { text: '累计在籍和不在籍男女生人数', left: 'center' },
      tooltip: { trigger: 'axis' },
      legend: { top: 'bottom' },
      xAxis: { type: 'category', data: ['在籍男', '在籍女', '不在籍男', '不在籍女'] },
      yAxis: { type: 'value' },
      series: [
        { name: '人数', type: 'bar', data: [0, 0, 0, 0] }
      ]
    };
    inSchoolStatusChart.setOption(inSchoolStatusChartOption);

    const classGenderPieChartOption = {
      title: { text: '各个班级的男女人数 (累计)', left: 'center' },
      tooltip: { trigger: 'item' },
      legend: { bottom: '0' },
      series: [
        {
          name: '人数',
          type: 'pie',
          radius: '50%',
          data: []
        }
      ]
    };
    classGenderPieChart.setOption(classGenderPieChartOption);

    const semesterClassGenderBarChartOption = {
      title: { text: '不同学期各个班级的男女人数 (累计)', left: 'center' },
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      legend: { top: 'bottom' },
      xAxis: { type: 'category', data: [] }, // 班级列表
      yAxis: { type: 'value' },
      series: [] // 按学期的系列数据
    };
    semesterClassGenderBarChart.setOption(semesterClassGenderBarChartOption);

    // 累计数据处理函数
    socket.on('kafka-message', (message) => {
      const parsedMessage = JSON.parse(message.data);
      const introduction = parsedMessage.introduction;
      const result = parsedMessage.result;

      if (introduction.includes('统计所有男女人数各自的总和')) {
        const match = result.match(/Male: (\d+\.?\d*), Female: (\d+\.?\d*), Total: (\d+\.?\d*)/);
        if (match) {
          cumulativeData.genderTotal.male += parseFloat(match[1]);
          cumulativeData.genderTotal.female += parseFloat(match[2]);
          cumulativeData.genderTotal.total += parseFloat(match[3]);

          genderTotalChartOption.series[0].data = [
            { name: '男', value: cumulativeData.genderTotal.male },
            { name: '女', value: cumulativeData.genderTotal.female }
          ];
          genderTotalChart.setOption(genderTotalChartOption);
        }
      }

      if (introduction.includes('统计各个学期男女人数总和')) {
        const entries = result.split(';').map(entry => {
          const match = entry.match(/Semester: (\d+), Gender: (\d+), Count: (\d+)/);
          if (match) {
            const semester = match[1];
            const gender = match[2] === '1' ? 'male' : 'female';
            const count = parseInt(match[3], 10);

            if (!cumulativeData.semesterTotal[semester]) {
              cumulativeData.semesterTotal[semester] = { male: 0, female: 0 };
            }
            cumulativeData.semesterTotal[semester][gender] += count;
          }
        });

        const semesters = Object.keys(cumulativeData.semesterTotal);
        const maleCounts = semesters.map(s => cumulativeData.semesterTotal[s].male);
        const femaleCounts = semesters.map(s => cumulativeData.semesterTotal[s].female);

        semesterTotalChartOption.xAxis.data = semesters;
        semesterTotalChartOption.series[0].data = maleCounts;
        semesterTotalChartOption.series[1].data = femaleCounts;
        semesterTotalChart.setOption(semesterTotalChartOption);
      }

      if (introduction.includes('统计在籍和不在籍男女生人数')) {
        const match = result.match(/InSchool - Male: (\d+), Female: (\d+); NotInSchool - Male: (\d+), Female: (\d+)/);
        if (match) {
          cumulativeData.inSchoolStatus.inSchool.male += parseInt(match[1], 10);
          cumulativeData.inSchoolStatus.inSchool.female += parseInt(match[2], 10);
          cumulativeData.inSchoolStatus.notInSchool.male += parseInt(match[3], 10);
          cumulativeData.inSchoolStatus.notInSchool.female += parseInt(match[4], 10);

          inSchoolStatusChartOption.series[0].data = [
            cumulativeData.inSchoolStatus.inSchool.male,
            cumulativeData.inSchoolStatus.inSchool.female,
            cumulativeData.inSchoolStatus.notInSchool.male,
            cumulativeData.inSchoolStatus.notInSchool.female
          ];
          inSchoolStatusChart.setOption(inSchoolStatusChartOption);
        }
      }

      if (introduction.includes('统计各个班级的男女的人数')) {
        const entries = result.split(';').map(entry => {
          const match = entry.match(/Class: ([^,]+), Gender: ([^,]+), Count: (\d+)/);
          if (match) {
            const className = match[1];
            const gender = match[2];
            const count = parseInt(match[3], 10);

            if (!cumulativeData.classGender[className]) {
              cumulativeData.classGender[className] = { male: 0, female: 0 };
            }
            cumulativeData.classGender[className][gender] += count;
          }
        });

        const pieData = Object.entries(cumulativeData.classGender)
          .flatMap(([className, counts]) => [
            { name: `${className} (男)`, value: counts.male },
            { name: `${className} (女)`, value: counts.female }
          ]);
        classGenderPieChartOption.series[0].data = pieData;
        classGenderPieChart.setOption(classGenderPieChartOption);
      }

      if (introduction.includes('统计不同学期各个班级的男女的人数')) {
        const entries = result.split(';').map(entry => {
          const match = entry.match(/Semester: (\d+), Class: ([^,]+), Gender: ([^,]+), Count: (\d+)/);
          if (match) {
            const semester = match[1];
            const className = match[2];
            const gender = match[3];
            const count = parseInt(match[4], 10);

            if (!cumulativeData.semesterClassGender[semester]) {
              cumulativeData.semesterClassGender[semester] = {};
            }
            if (!cumulativeData.semesterClassGender[semester][className]) {
              cumulativeData.semesterClassGender[semester][className] = { male: 0, female: 0 };
            }
            cumulativeData.semesterClassGender[semester][className][gender] += count;
          }
        });

        const semesters = Object.keys(cumulativeData.semesterClassGender);
        const classes = [...new Set(Object.values(cumulativeData.semesterClassGender)
          .flatMap(obj => Object.keys(obj)))];

        const series = semesters.map(semester => ({
          name: `学期 ${semester}`,
          type: 'bar',
          stack: 'total', // 同一班级堆叠数据
          emphasis: { focus: 'series' },
          data: classes.map(className => {
            const classData = cumulativeData.semesterClassGender[semester][className] || {};
            const maleCount = classData.male || 0;
            const femaleCount = classData.female || 0;
            return maleCount + femaleCount; // 将男女人数合并
          })
        }));

        semesterClassGenderBarChartOption.xAxis.data = classes;
        semesterClassGenderBarChartOption.series = series;
        semesterClassGenderBarChart.setOption(semesterClassGenderBarChartOption);
      }
    });
  </script>
</body>
</html>
